var fs = require('fs');
var path = require('path');
var express = require('express');
var index = require('../index');
var router = express.Router();

var PostModel = require('../models/posts');
var StudentModel = require('../models/students');
var checkLogin = require('../middlewares/check').checkLogin;

// GET 教师录入学生学号
//   eg: GET /posts?author=xxx
router.get('/inputStudent', checkLogin, function(req, res, next) {
    var identity = req.session.user.identity;
    var student_id = req.session.user.student_id;

    if ('教师' == identity || '管理员' == identity) {
        StudentModel.getAllStudents()
            .then(function (students) {
                res.render('inputStudents', {
                    students: students
                });
            })
            .catch(function (e) {
                next(e);
            });
    } else {
        req.flash('error', '您没有这个权限');
        return res.redirect('back');
    }
});

// POST 录入学生学号和姓名
router.post('/inputStudent', function (req, res, next) {
    var author = req.session.user._id;
    var student_id = req.fields.student_id;
    var student_name = req.fields.student_name;
    try {
        if (!(student_name.length >= 1 && student_name.length <= 20)) {
            throw new Error('学生名字请限制在 1-20 个字符');
        }
        if (!(student_id.length >= 1 && student_id.length <= 20)) {
            throw new Error('学生学号请限制在 1-20 个字符');
        }
    } catch (e) {
        req.flash('error', e.message);
        return res.redirect('/back');
    }
    var student = {
        author: author,
        student_id : student_id,
        student_name: student_name
    }
    StudentModel.create(student)
        .then(function (result) {
            StudentModel.getAllStudents()
                .then(function (students) {
                    res.render('inputStudents', {
                        students: students
                    });
                })
                .catch(function (e) {
                    next(e);
                });
        })
        .catch(function (e) {
            req.flash('error', '输入错误或该学生已存在');
            res.redirect('back');
        })
});

module.exports = router;
